document.addEventListener('DOMContentLoaded', function() {
    const ctx = document.getElementById('chartCanvas').getContext('2d');
    let chart;
    let isDragging = false;
    let activeBar = null;

    // 初始化设置模态框
    const modal = document.getElementById("settingsModal");
    const settingsBtn = document.getElementById("settings");
    const closeBtn = document.getElementsByClassName("close")[0];
    const applyColorsBtn = document.getElementById("applyColors");


     // 打开设置模态框
     settingsBtn.addEventListener('click', function() {
        // 设置当前颜色为颜色选择器的值
        document.getElementById('maleColor').value = rgbToHex(chart.data.datasets[0].backgroundColor);
        document.getElementById('femaleColor').value = rgbToHex(chart.data.datasets[1].backgroundColor);
        modal.style.display = "block";
    });
    
    // 关闭模态框
    closeBtn.addEventListener('click', function() {
        modal.style.display = "none";
    });
    
    // 点击模态框外部关闭
    window.addEventListener('click', function(event) {
        if (event.target == modal) {
            modal.style.display = "none";
        }
    });
    
    // 应用颜色设置
    applyColorsBtn.addEventListener('click', function() {
        const maleColor = document.getElementById('maleColor').value;
        const femaleColor = document.getElementById('femaleColor').value;
        
        // 更新图表颜色
        chart.data.datasets[0].backgroundColor = maleColor;
        chart.data.datasets[0].borderColor = maleColor;
        chart.data.datasets[1].backgroundColor = femaleColor;
        chart.data.datasets[1].borderColor = femaleColor;
        
        chart.update();
        modal.style.display = "none";
    });
    
    // RGB转十六进制颜色值
    function rgbToHex(rgb) {
        if (rgb.startsWith('#')) return rgb;
        
        // 处理rgba格式
        const rgbValues = rgb.match(/\d+/g);
        if (!rgbValues || rgbValues.length < 3) return '#36a2eb';
        
        const r = parseInt(rgbValues[0]).toString(16).padStart(2, '0');
        const g = parseInt(rgbValues[1]).toString(16).padStart(2, '0');
        const b = parseInt(rgbValues[2]).toString(16).padStart(2, '0');
        
        return `#${r}${g}${b}`;
    }

    

    // 初始化图表
    function initChart() {
        chart = new Chart(ctx, {
            type: 'bar',
            data: {
                labels: ['一年级', '二年级'], // 初始类别
                datasets: [
                    {
                        label: '男生',
                        data: [6, 5], // 初始男生数据
                        backgroundColor: 'rgba(54, 162, 235, 0.8)',
                        borderColor: 'rgba(54, 162, 235, 1)',
                        borderWidth: 1,
                        barThickness: 50,
                    },
                    {
                        label: '女生',
                        data: [9, 8], // 初始女生数据
                        backgroundColor: 'rgba(255, 99, 132, 0.8)',
                        borderColor: 'rgba(255, 99, 132, 1)',
                        borderWidth: 1,
                        barThickness: 50,
                    }
                ]
            },
            options: {
                responsive: true,
                maintainAspectRatio: false,
                scales: {
                    y: {
                        beginAtZero: true,
                        min: 0,
                        ticks: {
                            stepSize: 1,
                            precision: 0,
                            color: '#666',
                            font: { size: 12 }
                        },
                        afterDataLimits: (scale) => {
                            scale.max = Math.ceil(scale.max);
                            scale.min = Math.floor(Math.max(0, scale.min));
                        }
                    },
                    x: {
                        barPercentage: 1.0,
                        ticks: {
                            color: '#333',
                            font: { size: 22, weight: 'bold' }
                        },
                        grid: { display: false }
                    }
                },
                plugins: {
                    legend: { labels: { font: { size: 12 } } },
                    tooltip: { enabled: false }
                },
                onHover: (event, chartElements) => {
                    event.native.target.style.cursor = chartElements[0] ? 'ns-resize' : 'default';
                }
            }
        });

        addDragInteraction();
        initializeDefaultData();
    }

    // 添加拖动交互功能
    function addDragInteraction() {
        const canvas = document.getElementById('chartCanvas');
        let startY, startValue;
    
        canvas.addEventListener('mousedown', (e) => {
            const points = chart.getElementsAtEventForMode(e, 'nearest', { intersect: true }, false);
            if (points.length) {
                isDragging = true;
                activeBar = points[0];
                startY = e.clientY;
                startValue = chart.data.datasets[activeBar.datasetIndex].data[activeBar.index];
                canvas.style.cursor = 'ns-resize';
            }
        });
    
        canvas.addEventListener('mousemove', (e) => {
            if (!isDragging || !activeBar) return;
            
            const deltaY = startY - e.clientY;
            const yAxis = chart.scales.y;
            const pixelToValueRatio = (yAxis.max - yAxis.min) / yAxis.height;
            
            let newValue = Math.max(0, Math.round(startValue + deltaY * pixelToValueRatio));
            
            chart.data.datasets[activeBar.datasetIndex].data[activeBar.index] = newValue;
            
            updateInputField(activeBar.datasetIndex, activeBar.index, newValue);
            
            // 拖动后强制更新图表范围
            const currentMax = Math.max(...chart.data.datasets.flatMap(d => d.data));
            const currentMin = Math.min(...chart.data.datasets.flatMap(d => d.data));
            chart.options.scales.y.max = Math.max(10, Math.ceil(currentMax * 1.1));
            chart.options.scales.y.min = Math.max(0, Math.floor(currentMin * 0.9));
            
            chart.update();
        });
    
        canvas.addEventListener('mouseup', () => {
            isDragging = false;
            activeBar = null;
            canvas.style.cursor = 'default';
        });

        canvas.addEventListener('mouseleave', () => {
            isDragging = false;
            activeBar = null;
            canvas.style.cursor = 'default';
        });
    }

    // 更新输入字段
    function updateInputField(datasetIndex, dataIndex, value) {
        const dataItems = document.querySelectorAll('.dataItem');
        if (dataItems.length > dataIndex) {
            const inputField = datasetIndex === 0 
                ? dataItems[dataIndex].querySelector('.maleInput')
                : dataItems[dataIndex].querySelector('.femaleInput');
            if (inputField) {
                inputField.value = value;
            }
        }
    }

    // 更新图表数据
    function updateChart() {
        const dataItems = document.querySelectorAll('.dataItem');
        const categories = [];
        const maleData = [];
        const femaleData = [];
    
        dataItems.forEach(item => {
            const category = item.querySelector('.categoryInput').value;
            const male = parseInt(item.querySelector('.maleInput').value) || 0;
            const female = parseInt(item.querySelector('.femaleInput').value) || 0;
    
            if (category) {
                categories.push(category);
                maleData.push(male);
                femaleData.push(female);
            }
        });
    
        chart.data.labels = categories;
        chart.data.datasets[0].data = maleData;
        chart.data.datasets[1].data = femaleData;
        
        // 动态调整y轴范围
        const currentMax = Math.max(...maleData, ...femaleData);
        const currentMin = Math.min(...maleData, ...femaleData);
        
        // 设置合理的y轴范围
        chart.options.scales.y.max = Math.max(10, Math.ceil(currentMax * 1.1)); // 留10%余量，最小为10
        chart.options.scales.y.min = Math.max(0, Math.floor(currentMin * 0.9)); // 留10%余量，最小为0
        
        chart.update();
    }

    // 初始化默认数据
    function initializeDefaultData() {
        const defaultData = [
            { category: '一年级', male: 6, female: 9 },
            { category: '二年级', male: 5, female: 8 }
        ];

        defaultData.forEach(data => {
            addDataItem(data.category, data.male, data.female);
        });
    }

    // 添加数据项
    function addDataItem(category = '', male = 0, female = 0) {
        const newItem = document.createElement('div');
        newItem.className = 'dataItem';
        newItem.innerHTML = `
            <div class="input-group">
                <label>类别: <input type="text" class="categoryInput" value="${category}"></label>
                <label>男生: <input type="number" class="maleInput" value="${male}" min="0"></label>
                <label>女生: <input type="number" class="femaleInput" value="${female}" min="0"></label>
                <button class="remove">删除</button>
            </div>
        `;
        
        newItem.querySelector('.remove').addEventListener('click', function() {
            this.closest('.dataItem').remove();
            updateChart();
        });
        
        newItem.querySelectorAll('input').forEach(input => {
            input.addEventListener('input', updateChart);
        });
        
        document.getElementById('dataForm').appendChild(newItem);
        updateChart();
    }

    // 重置功能
    function resetChart() {
        document.getElementById('dataForm').innerHTML = '';
        initializeDefaultData();
        document.getElementById('showMaleOnly').classList.remove('toggle-on');
        document.getElementById('showFemaleOnly').classList.remove('toggle-on');
        document.getElementById('showMaleOnly').textContent = '仅男生';
        document.getElementById('showFemaleOnly').textContent = '仅女生';
    }

    // 事件监听器
    document.getElementById('addData').addEventListener('click', function() {
        addDataItem();
    });

    document.getElementById('view').addEventListener('click', resetChart);

    document.getElementById('showMaleOnly').addEventListener('click', function() {
        const showMaleOnly = !chart.data.datasets[1].hidden;
        chart.data.datasets[1].hidden = showMaleOnly;
        chart.data.datasets[0].hidden = false;
        chart.update();
        this.classList.toggle('toggle-on');
        document.getElementById('showFemaleOnly').classList.remove('toggle-on');
        this.textContent = showMaleOnly ? '显示全部' : '仅男生';
        document.getElementById('showFemaleOnly').textContent = '仅女生';
    });

    document.getElementById('showFemaleOnly').addEventListener('click', function() {
        const showFemaleOnly = !chart.data.datasets[0].hidden;
        chart.data.datasets[0].hidden = showFemaleOnly;
        chart.data.datasets[1].hidden = false;
        chart.update();
        this.classList.toggle('toggle-on');
        document.getElementById('showMaleOnly').classList.remove('toggle-on');
        this.textContent = showFemaleOnly ? '显示全部' : '仅女生';
        document.getElementById('showMaleOnly').textContent = '仅男生';
    });

    // 初始化
    initChart();
});